#!/usr/bin/env python2.5
# -*- coding: UTF-8 -*-
  
##import wsgiref.util         usefull utils nooverhead since  run_wsgi_app imports those too  

  
from nmpacks.milonpy import NMhtml as html
from nmpacks.milonpy import NMserver as NMserver
#from nmpacks.milonpy import NMutl as utl
#from nmpacks.milonpy import NMtbl as tbl   

#import locale
 
run_wsgi_app = NMserver.webapp.util.run_wsgi_app
webapp=NMserver.webapp
datetime=NMserver.datetime 



class cntr_panelRQH(NMserver.ReqHadlerNM):  
    cookieName, cookiePath=('geognos' , '/geo/')
    isStaticContent=False
    useCashe = 0  
    tmplHeader = """<p id="nm_beta"  class ="nm-inline">  * βeta </p> """   
    tmplHead="""
      <title>App Engine Admin Panel</title> 
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" >
      <meta name="author" content="geognos.com" > 
      <meta name="copyright" content="(c) 2009 geognos.com" >
      <meta name="robots" content="noindex,nofollow" >       
      <link rel="stylesheet" href="http://yui.yahooapis.com/2.7.0/build/reset-fonts-grids/reset-fonts-grids.css" type="text/css">
      <link rel="stylesheet" href="/media/css/yuinm.css" type="text/css" media="screen, projection">   
    """
    tmplFooter="""
        <div  class="nm-cnt01">   
         |&nbsp;<a href="/geo/en/help.html">Help</a> 
         |&nbsp;<a href="http://gaengine.blogspot.com/"  >Blog</a> 
         |&nbsp;<a href="http://code.google.com/p/geognos/" >Project site</a>  
     </div>    
     <div class="nm-cnt02">  
         <a target="_blank" href = "http://code.google.com/appengine/" > 
           <img class="nm_imggae" src="http://code.google.com/appengine/images/appengine-noborder-120x30.gif" alt="Powered by Google App Engine" title="Powered by Google App Engine">
         </a>  
     </div>       
     <div  class="nm-cnt03">  
         Visualizations by <a href = "http://code.google.com/apis/visualization/">Google Visualization API </a>
         &nbsp;|&nbsp;Dynamic maps by <a  href = "http://code.google.com/apis/maps/documentation/v3/">Google Maps API v3</a>
         &nbsp;|&nbsp;Dynamic translations by <a  href = "http://code.google.com/apis/ajaxlanguage/">Google AJAX Language API</a>
     </div>  
    """
    tmplMnu="""
       <ul>cashe</ul>
          <li class="nm-cnt00 nm-even"><a href="/nmops/cashe/memstats/">MemCashe statistics</a></li> 
          <li class="nm-cnt01 nm-odd"><a href="/nmops/cashe/memflush_all/">MemCashe flush all</a></li> 
          <li class="nm-cnt02 nm-even"><a href="/nmops/cashe/dbflush_all/">DBCashe flush all</a></li>
          <li class="nm-cnt03 nm-odd"><a href="/nmops/cashe/flush_sitemap/">flush sitemap</a></li>  
          <li class="nm-cnt04 nm-even"><a href="/nmops/cashe/resetCountryListsMenus/">resetCountryListsMenus</a></li>
          <li class="nm-cnt05 nm-odd"> <a href="/adminops/en/db/country_list/add/foo/">Add Country list</a></li>
          <li class="nm-cnt06 nm-even"><a href="geo/en/countries/CountryCodes.html">test adding fields</a></li>
       <ul>  
    """
    def getC(self, opGroup, operation, arg):
        def flush(key):
            memcache.delete(key, seconds=0, namespace=None) 
            dbCashe.flush_byKey(key)
        def flush_sitemap():flush("/sitemap.xml") 
        dbCashe  = NMserver.NM_DScashe()
        memcache = NMserver.memcache
        #print(opGroup, operation, arg)  
        ytml=html.y_html(html.y_html.width.doc3,   sbar=html.y_html.sidebar.t3)      
        nm_divRowcontents= html.div(html.incl(''), 'id=\"nm_divrowcontents"')
        nm_divRow=html.rowCont("OPERATION", nm_divRowcontents , "", 2)   
        if  opGroup=='cashe':  
            #nm_divRowcontents= html.div(nm_flagcontents, 'id=\"nm_divrowcontents"') 
            nm_divRow=html.rowCont("Memcashe", nm_divRowcontents , "", 2)  
            if  operation=='memflush_all':memcache.flush_all() 
            elif operation=='dbflush_all':
                dbCashe.flush_all() 
            elif operation=='flush_sitemap':flush_sitemap()     
            elif operation=='resetCountryListsMenus':
    #               lst=('All', 'Popular', 'Latest', 'Geography', 'Demographics', 'Economy', 'Goverment')
    #               keybase='/geo/en/countries-list-menu/'
    #               for item in lst:
    #                   key=keybase+item+'.html?'
    #                   flush(key)
                r=dbCashe.getBetween('/geo/en/countries-list-menu/','/geo/en/countries-list-menu/a')
                for item in r:flush (item.key().name())  
                flush_sitemap() 
            contents=html.rowCont("Statistics", nm_divRowcontents , "", 3)  
            stats = NMserver.memcache.get_stats().items() 
            
            tmp=int(stats[3][1]) 
            stats = [ [x[0].replace('_', ' '), str( x[1]) , ' '] for x in stats]
            stats[3][1]= '%d hour(s) : %d minutes'  %(tmp/3600,  (tmp % 3600)/60 )  
            stats = html.table(stats, attributes='',caption = False, headerlst = [], footerlst= [], tagColums=True)
            contents.insertContents(stats)
            nm_divRow.insertContents(contents) 
        elif opGroup=='dbcashe':    
            pass
          
        ytml.doc_bd_cnts.insertContents(nm_divRow)     
        #site = ' geognos.com ' 
        #self.tmplD={'description': site + arg + ' page','inclmap':False,'title':site + arg, 'keywords':'', 'lang':'', 'frmAction': "/geo/switch/", 'frm2Action':"/geo/switch/" , 'frmOptions':''}        
        ytml.setdefaults('Admin Operations',  self.tmplFooter , html.p(''), False,  'nm-operations')     
        ytml.cntr_panel.insertContents(html.incl(self.tmplHeader)) 
        ytml.html_head.insertContents(html.incl (self.tmplHead))    
        ytml.mnuConts.insertContents([html.a('Home','class=\"nm_cont_gl\"', '/' )] )    
        nm_sidebar_l1_cont = html.rowCont ("Menu", self.tmplMnu , "nm_sidebar_l1_cont", 2) 
         
        ytml.doc_bd_sidebar.insertContents(html.div(nm_sidebar_l1_cont,'id=\"nm_sidebar_l1\" class=\"nm-lev-02\"' ))    
        return ytml()


application = webapp.WSGIApplication(
                                     [ 
                                      (r"/nmops/(?P<opGroup>.*?)/(?P<operation>.*?)/(?P<arg>.*?)", cntr_panelRQH),
                                      (r"(.*)", cntr_panelRQH)],
                                     debug=True)

def main(): 
    run_wsgi_app(application)
if __name__ == "__main__":
    main() 
